(defmacro while (test &rest body)
  `(do ()
       ((not ,test))
     ,@body))


(let ((x 0))
  (while (< x 10)
    (princ x)
    (incf x)))


;;;;Quicksort on page 165

(defun quicksort (vec l r)
	(format t "Range is ~A - ~A~%" l r)
	(format t "Vector is ~A~%" vec)
	(let ((i l)
				(j r)
				(p (svref vec (round (+ l r) 2))))
	  (format t "Pivot is ~A~%" p)			
		(while (<= i j)
			(while (< (svref vec i) p) (incf i))
			(while (> (svref vec j) p) (decf j))
			(when (<= i j)
				(format t "Swaping  ~A at ~A and ~A at ~A ~%" (svref vec i) i (svref vec j) j)
				(rotatef (svref vec i) (svref vec j))
				(incf i)
				(decf j))) 
		(if (>= (- j l) 1) (quicksort vec l j))
		(if (>= (- r i) 1) (quicksort vec i r)))
	vec)
				
	
;;;;Macro ntimes with gensyms
(defmacro ntimes (n &rest body)
  (let ((g (gensym))
	(h (gensym)))
		`(let ((,h ,n))
			(do ((,g 0 (+ ,g 1)))
					((>= ,g ,h))
				,@body))))

;;;;Macros utilities on page 170
(defmacro for (var start stop &body body)
	(let ((gstop (gensym)))
		`(do ((,var ,start (1+ ,var))
					(,gstop ,stop))
				 ((> ,var ,gstop))
			 ,@body))) 

(defmacro in (x &rest others)
	(let ((gx (gensym)))
		`(let ((,gx ,x))
			 (if (eql ,gx (car ,@others))
			 	 T
			   (in ,gx (cdr ,@others))))))

(defmacro avg (&rest args)
    `(/ (+ ,@args) ,(length args)))

(defmacro with-gensym (var &body body)
  `(let ,(mapcar #'(lambda (x)
                     `(,x (gensym)))
                 var)
     ,@body))
        
   
(defmacro nomod (lst &body body)
    (with-gensym (vals)
        `(let ((,vals (list ,@ lst))) 
            ,@body
            ,@(let (acc)
                (dotimes (x (length lst) acc)
                    (push `(setf ,(nth x lst) (nth ,x ,vals)) 
                          acc))))))

(defmacro nomod1 (lst &body body)
  (with-gensym (vals)
    `(let ((,vals (list ,@lst)))
       ,@ body
       (setf ,@(mapcan #'(lambda (var)
                           (list var `(nth ,(position var lst) ,vals)))
                       lst))))) 

(defmacro reset-var (lst &body body)
  `(let (,@lst)
     ,@body))

